package com.aruba.paging2.paging.model;

import androidx.annotation.NonNull;
import androidx.paging.PageKeyedDataSource;
import androidx.paging.PositionalDataSource;

import com.aruba.paging2.api.RetrofitClient;
import com.aruba.paging2.entity.Movie;
import com.aruba.paging2.entity.Movies;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by aruba on 2021/9/17.
 */
public class MovieDataSource extends PageKeyedDataSource<Integer, Movie> {
    public static final int PER_PAGE = 8;
    public static final int FIRST_PAGE = 1;

    @Override
    public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull LoadInitialCallback<Integer, Movie> callback) {
        RetrofitClient.getInstance().getApi()
                .getMovies(FIRST_PAGE, PER_PAGE)
                .enqueue(new Callback<Movies>() {
                    @Override
                    public void onResponse(Call<Movies> call, Response<Movies> response) {
                        //第一次加载，上一页page为null，下一页传入page+1
                        callback.onResult(response.body().movies, null, FIRST_PAGE + 1);
                    }

                    @Override
                    public void onFailure(Call<Movies> call, Throwable t) {

                    }
                });
    }

    @Override
    public void loadBefore(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, Movie> callback) {

    }

    @Override
    public void loadAfter(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, Movie> callback) {
        RetrofitClient.getInstance().getApi()
                .getMovies(params.key, PER_PAGE)
                .enqueue(new Callback<Movies>() {
                    @Override
                    public void onResponse(Call<Movies> call, Response<Movies> response) {
                        if(response.body() == null){
                            return;
                        }
                        //把数据传递给PagedList
                        Integer nextKey = response.body().hasMore ? params.key + 1 : null;
                        callback.onResult(response.body().movies, nextKey);
                    }

                    @Override
                    public void onFailure(Call<Movies> call, Throwable t) {

                    }
                });
    }
}